package com.orhon.smartcampus.modules.systemctl.mutation;

import java.util.Date;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import com.alibaba.fastjson.JSON;
import com.orhon.smartcampus.basicComponents.Result;
import com.orhon.smartcampus.modules.systemctl.dao.MenusDao;
import com.orhon.smartcampus.modules.systemctl.dao.ModulesDao;
import com.orhon.smartcampus.modules.systemctl.entity.Menus;
import com.orhon.smartcampus.modules.systemctl.entity.Modules;
import com.orhon.smartcampus.modules.systemctl.gqlInputModel.GQLModuleInput;
import com.orhon.smartcampus.modules.systemctl.inputMapper.ModuleInputMapper;

import graphql.schema.DataFetcher;
import graphql.schema.DataFetchingEnvironment;

@Component
public class AddModulesMutation implements DataFetcher {

    @Autowired
    ModulesDao modulesDao;

    @Autowired
    MenusDao menusDao;

    /**
     * 新增/修改模块信息
     * editor : ths
     */
    @Override
    public Object get(DataFetchingEnvironment environment) throws Exception {
        GQLModuleInput input = ModuleInputMapper.MAPPER.mapInput(environment.getArgument("inputData"));

        Modules modules = null;

        if (input.getId() != null) {
            modules = modulesDao.get(Modules.class, input.getId());
            modules.setUpdatedAt(new Date());
        } else {
            modules = new Modules();
            modules.setCreatedAt(new Date());
        }
        if(input.getModule_name() != null){

            modules.setModuleName(JSON.toJSONString(input.getModule_name()));
        }
        if(input.getCategory() != null){

            modules.setCategory(input.getCategory());
        }
        if(input.getModule_order() != null){

            modules.setModuleOrder(input.getModule_order());
        }
        if(input.getHome_id() != null) {
            modules.setHome(menusDao.get(Menus.class, input.getHome_id()));
        }
        if(input.getMark() != null){

            modules.setMark(input.getMark());
        }
        if(input.getIcon() != null){

            modules.setIcon(input.getIcon());
        }
        if(input.getClients() != null){

            modules.setClients(JSON.toJSONString(input.getClients()));
        }
        if(input.getMeta() != null){

            modules.setMeta(input.getMeta());
        }
        if(input.getStatus() != null){

            modules.setStatus(input.getStatus());
        }
        try{
            modulesDao.saveOrUpdate(modules);
        }
        catch (Exception e){
            return Result.error(500,""+e);
        }
        return Result.ok();
    }
}

